<?php

namespace pdfreader;

use Smalot\PdfParser\Parser;
use Smalot\PdfParser\Element\Text;

class PdfReader
{
    public function readPdfFile($filePath)
    {
         // 检查文件是否存在，如果是远程文件，这里仅检查 URL 是否有效
        if (!filter_var($filePath, FILTER_VALIDATE_URL) && !file_exists($filePath)) {
            return "找不到指定的文件";
        }
       
        $parser = new Parser();
        $pdf = $parser->parseFile($filePath);
        $textLines = explode("\n", $pdf->getText()); // 假设 getText 返回的是全文文本
        $tree = [];
        $currentChapter = null;
        $currentSection = null;
        
        foreach ($textLines as $line) {
            $line = rtrim($line, "\r\n");
            // 正则表达式匹配章节
            if (preg_match('/###(第[一二三四五六七八九十百千万零]+[章回卷])\s*(.*?)###/u', $line, $matches)) {
                // 章匹配成功
                if ($currentChapter !== null) {
                    // 保存上一个章节
                    $tree[] = $currentChapter;
                }
                $currentChapter = [
                    'chapter_number' => $matches[1],
                    'chapter_title' => $matches[2],
                    'sections' => []
                ];
                $currentSection = null; // 重置当前节
            } 
            // 正则表达式匹配节
            elseif (preg_match('/###(第[一二三四五六七八九十百千万零]+节)\s*(.*?)###/u', $line, $matches) && $currentChapter !== null) {
                // 节匹配成功
                if ($currentSection !== null) {
                    // 保存上一个节
                    $currentChapter['sections'][] = $currentSection;
                }
                $currentSection = [
                    'section_number' => $matches[1],
                    'section_title' => $matches[2],
                    'content' => ''
                ];
            } else {
                // 内容属于当前节
                if ($currentSection !== null) {
                    $currentSection['content'] .= $line . "\n";
                }
            }
        }
        
        // 循环结束后，保存最后一个章节和节
        if ($currentChapter !== null) {
            if ($currentSection !== null) {
                // 保存最后一个节
                $currentChapter['sections'][] = $currentSection;
            }
            $tree[] = $currentChapter;
        }
        return $tree;
    }
}